package com.neusoft.bizcore.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LogFilter implements Filter {

    @Override
    public void init(final FilterConfig filterConfig) throws ServletException {
        System.out.println("--------------logFilter 过滤器初始化------------");
    }

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
            throws IOException, ServletException {
        final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        final ServletRequest requestWrapper = new JsonBodyHttpRequestWrapper(httpServletRequest);
        this.printRequest(requestWrapper);
        chain.doFilter(requestWrapper, response);
    }

    private void printRequest(final ServletRequest servletRequest) {
        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        final String uri = request.getRequestURI();
        String requestBody = "";
        final String requestContentType = request.getHeader(HttpHeaders.CONTENT_TYPE);
        if (requestContentType != null) {
            //  只拦截 json 请求的参数
            if (requestContentType.startsWith(MediaType.APPLICATION_JSON_VALUE)
                    || requestContentType.startsWith(MediaType.APPLICATION_XML_VALUE)) {
                requestBody = this.getRequestBody(request);
                LogFilter.log.info("请求开始 url ==={}", uri);
                LogFilter.log.info("请求开始 参数 ==={}", requestBody);
            }
        }
    }

    private String getRequestBody(final HttpServletRequest request) {
        final int contentLength = request.getContentLength();
        if (contentLength <= 0) {
            return "";
        }
        try {
            return IOUtils.toString(request.getReader());
        } catch (final IOException e) {
            LogFilter.log.error("获取请求体失败", e);
            return "";
        }
    }

}
